import org.junit.Test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * User: 5
 * Date: 16-12-20
 * 模拟消费者-生产者
 */
public class PrintLog {
    @Test

    public void test() {
        final BlockingQueue<String> logs = new ArrayBlockingQueue<String>(35000);
        ExecutorService executorService = Executors.newCachedThreadPool();   //可缓存线程池
        Log log = new Log(logs);
        for (int i = 0; i < 40; i++) {
            executorService.submit(log);
        }
        //400w 插入  --5线程放到队列中，10线程轮流去保存数据。//比一个一个的保存要快些吧
        for (int i = 0; i < 16000000; i++) {
            try {
                logs.put(i + "");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Log implements Runnable {
    private BlockingQueue<String> logs = null;

    Log(BlockingQueue<String> blockingQueue) {
        this.logs = blockingQueue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                parseLog(logs.take());    //阻塞
//                            Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void parseLog(String log) {
//        System.out.println(log + " -- " + Thread.currentThread()); //输出到控制台相当费时。
    }
}